package com.ljcalc.business.components.fetchers;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.util.LinkedList;

import org.apache.xerces.xni.parser.XMLInputSource;
import org.apache.xerces.xni.parser.XMLParserConfiguration;
import org.cyberneko.html.HTMLConfiguration;

import com.ljcalc.business.components.ConnectionFactory;
import com.ljcalc.business.components.NumberPercentage;
import com.ljcalc.business.components.NumberPercentageItemListHandler;

public class NumberPercentageFetcher extends ContentFetcher {

	private LinkedList<NumberPercentage> list = null;
	
	public NumberPercentageFetcher(String url) {   
		super(url);
	}
	
	public NumberPercentageFetcher(){
		this("http://svenskaspel.se/common/infopopup/statistik.aspx?product=8");
	}
	
	public LinkedList<NumberPercentage> getList(){
		return list;
	}

	public Object getNextElement() {
		return null;
	}

	/**
	 * Clear all tags only leave the content
	 */
	
	public int loadContent() throws IOException {
		if(url==null||!goodUrlFormat)
			return 0;
		
		NumberPercentageItemListHandler handler = new NumberPercentageItemListHandler();
		XMLParserConfiguration xmlReaderParser = new HTMLConfiguration();
		xmlReaderParser.setDocumentHandler(handler);
		URLConnection connection = ConnectionFactory.createURLConnection(url) ;
		connection.connect();
		String encoding = connection.getContentEncoding();
        Reader reader = new InputStreamReader(new BufferedInputStream(url.openStream())); 
		XMLInputSource src = new XMLInputSource(null, null, null, reader, encoding);	  
        //put the map into a centralized content container
		xmlReaderParser.parse(src);
		reader.close();		
		list = handler.getList();
		
		
		return handler.getList().size();
	}

}
